<%--
  Created by IntelliJ IDEA.
  User: 小袁啊
  Date: 2024/10/16
  Time: 上午10:50
  To change this template use File | Settings | File Templates.
--%>
<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%--    引入vuejs和axios--%>
    <script src="/js/vue.js"></script>
    <script src="/js/axios.main.js"></script>
    <%--    引入Element--%>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
    <%--    添加按钮--%>
    <el-button type="primary" @click="dialogFormVisible1 = true">快来添加吧</el-button>
    <%--    添加学生对话框--%>
    <el-dialog title="添加学生" :visible.sync="dialogFormVisible1">
<%--        添加关闭事件--%>
        <el-form :model="form1" :rules="rules" ref="form1" @close="resetForm">
            <%--    解释
                    label-width:表单标签的宽度，单位为px，不设置则自动分配。
                    class：表单元素的自定义类名。
                    :show-file-list：是否显示文件列表。
                    on-success: 上传成功回调
                    before-upload: 上传前回调
                    :src：图片路径。
                    class：图片样式。
                           图片上传         --%>
            <el-form-item label="头像" :label-width="formLabelWidth" prop="headimg">
                <el-upload
                        class="avatar-uploader"
                <%--                        请求的路径--%>
                        action="/utils/ossShang"
                        :show-file-list="false"
                <%--                        请求成功后的回调函数，参数为上传成功后的返回数据。--%>
                        :on-success="handleAvatarSuccess"
                <%--                        请求前的回调函数，返回值为false或返回promise时，停止上传。--%>
                        :before-upload="beforeAvatarUpload">
                    <%--                     图片显示的路径--%>
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>

            <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
                <el-input v-model="form1.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
                <el-input v-model.number="form1.age" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
                <el-radio-group v-model="form1.gender">
                    <el-radio-button label="男" value="男"></el-radio-button>
                    <el-radio-button label="女" value="女"></el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="生日" :label-width="formLabelWidth" prop="birthday">
                <el-date-picker
                        v-model="form1.birthday"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="班级" :label-width="formLabelWidth" prop="clazzId">
                <el-select v-model="form1.clazzId" placeholder="请选择班级">
                    <el-option v-for="c in clazzList" :label="c.name" :value="c.id"></el-option>
                </el-select>
            </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible1 = false">取 消</el-button>
            <el-button type="primary" @click="addStudent()">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog title="修改学生" :visible.sync="dialogFormVisible2">
        <el-form :model="form2" :rules="rules" ref="form2">
            <el-form-item label="头像" :label-width="formLabelWidth" prop="headimg">
                <el-upload
                        class="avatar-uploader"
                <%--                        请求的路径--%>
                        action="/utils/ossShang"
                        :show-file-list="false"
                <%--                        请求成功后的回调函数，参数为上传成功后的返回数据。--%>
                        :on-success="handleAvatarSuccess"
                <%--                        请求前的回调函数，返回值为false或返回promise时，停止上传。--%>
                        :before-upload="beforeAvatarUpload">
                    <%--                     图片显示的路径--%>
                    <img v-if="form2.headimg" :src="form2.headimg" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
                <el-input v-model="form2.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="age" :label-width="formLabelWidth" prop="age">
                <el-input v-model.number="form2.age" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="性别" :label-width="formLabelWidth">
                <el-radio-group v-model="form2.gender">
                    <el-radio-button label="男" value="男"></el-radio-button>
                    <el-radio-button label="女" value="女"></el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="生日" :label-width="formLabelWidth">
                <el-date-picker
                        v-model="form2.birthday"
                        type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="选择日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="班级" :label-width="formLabelWidth">
                <el-select v-model="form2.clazzId" placeholder="请选择班级">
                    <el-option v-for="c in clazzList" :label="c.name" :value="c.id"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible2 = false">取 消</el-button>
            <el-button type="primary" @click="update()">确 定</el-button>
        </div>
    </el-dialog>

    <el-table
    <%--        data表示数据源
    --%>
            :data="students"
            border
            style="width: 95%">
        <el-table-column
        <%--            prop表属性名
                        label显示的文字
                        width列宽
        --%>
                prop="id"
                label="编号">
        </el-table-column>
        <el-table-column
                prop="name"
                label="姓名">
        </el-table-column>
        <el-table-column
                prop="age"
                label="年龄">
        </el-table-column>
        <el-table-column
                prop="gender"
                label="性别">
        </el-table-column>
        <el-table-column
                prop="birthday"
                label="生日">
        </el-table-column>
        <el-table-column
                prop="clazz.name"
                label="班级">
        </el-table-column>
        <%--        头像--%>
        <el-table-column
                label="头像">
            <template slot-scope="scope">
                <img :src="scope.row.headimg" width="60px">
            </template>
        </el-table-column>
        <el-table-column
        <%--            label= 设置成超链接或者执行跳转方法，跳转其他页面--%>
                label="操作"
                wight="200px">
            <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" circle @click="getById(scope.row.id)">
                    编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" @click="deleteById(scope.row.id)">
                    删除
                    <i class="el-icon-upload el-icon--right"></i>
                </el-button>
            </template>
        </el-table-column>
    </el-table>
        <%--        分页功能
                @size-change：每页数据量改变时会触发，返回改变后的每页数据量
                @current-change：页码改变时会触发，返回改变后的页码
                :current-page="currentPage4"：当前页，默认为 1
                :page-sizes="[100, 200, 300, 400]"：每页可以显示的条数，数组类型
                :page-size="100"：默认每页显示 100 条
                layout="total, sizes, prev, pager, next, jumper"：
                        总条数，每页条数，上一页，页码，下一页，跳转页码
                total：数据总数
        --%>
        <el-pagination

                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[2, 3, 5, 10]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>
</div>
</body>
<script>
    // 自定义校验 性别
    var checkAge = (rule, value, callback) => {
        console.log(value);
        console.log(value);
        setTimeout(() => {
            if (!Number.isInteger(value)) {
                callback(new Error('请输入数字值'));
            } else {
                if (value < 18) {
                    callback(new Error('必须年满18岁'));
                } else {
                    callback();
                }
            }
        }, 200);
    };
    // 定义一个对象，用来接收数据
    let app = new Vue({
        el: '#app',
        data: {
            //定义一个变量，用来接收数据
            students: undefined,//不知道什么类型
            dialogFormVisible1: false,//添加对话框的显示和隐藏
            dialogFormVisible2: false,//修改对话框的显示和隐藏
            formLabelWidth: '120px',//表单的标签的宽度
            imageUrl: '',//图片路径
            clazzList: undefined,//班级列表
            currentPage:1,//当前页码
            pageSize:2,//每页显示的条数
            total:0,//总记录数

            rules:{//校验规则
                headimg: [
                    {required: true, message: '请上传图片', trigger: 'blur'}
                ],
                name: [
                    {required: true, message: '请输入活动名称', trigger: 'blur'},
                    {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
                ],
                age: [
                    // // 自定义校验
                    // { validator: checkAge, trigger: 'blur' },
                    {required: true, message: '请输入活动名称', trigger: 'blur'},
                    {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
                ],
                gender: [
                    {required: true, message: '请选择性别', trigger: 'blur'}
                ],
                birthday: [
                    {required: true, message: '请选择生日', trigger: 'blur'}
                ],
                clazzId: [
                    {required: true, message: '请选择班级', trigger: 'blur'}
                ],
            },
            // 添加表单的数据
            form1: {
                name: '',
                age: '',
                gender: '',
                birthday: '',
                headimg: '',
                clazzId: '',
            },
            // 修改学生的表单的数据
            form2: {
                id: '',
                name: '',
                age: '',
                gender: '',
                birthday: '',
                headimg: '',
                clazzId: '',
            }
        },
        //在页面加载的时候就发送请求，获取数据
        created() {
            this.getAll();
            this.getClazz();
        },
        // 定义方法
        methods: {
            // 每页数据量改变
            handleSizeChange(val) {
                this.pageSize=val;//把改变值赋值给pageSize
                this.getAll();
            },
            // 页码改变
            handleCurrentChange(val) {
                this.currentPage=val;
                this.getAll();
            },

            //获取所有学生信息
            getAll() {
                axios.get("/student/getAll?pageNum="+this.currentPage+"&pageSize="+this.pageSize).then(resp => {
                    // console.log(resp.data.data.pageNum);
                    // console.log(resp.data.data.pageSize);
                    if (resp.data.code === 200) {
                        //把返回的数据赋值给students
                        this.students = resp.data.data.list;
                        //分页信息
                        // 当前页码
                        this.currentPage = resp.data.data.pageNum;
                        this.pageSize = resp.data.data.pageSize;
                        this.total=resp.data.data.total;
                    } else {
                        alert(resp.data.msg);
                    }
                })
            },
            //查询所有的班级
            getClazz() {
                axios.get("/clazz/getAll").then(resp => {
                    //alert(resp.data.data);
                    //把数据赋值给form
                    this.clazzList = resp.data.data;
                    console.log(resp);
                })
            },
            //查找一个学生
            getById(id) {
                axios.get("/student/getById?id=" + id).then(resp => {
                    //alert(resp.data.id);
                    //把数据赋值给form
                    this.form2 = resp.data.data;
                    //显示对话框
                    this.dialogFormVisible2 = true;
                })
            },
            //修改学生
            update() {
                axios.put("/student/update", this.form2).then(resp => {
                    console.log(resp);
                    if (resp.data.code === 200) {
                        //添加成功，重新加载数据
                        this.dialogFormVisible2 = false;
                        this.$notify({
                            title: '修改成功',
                            message: resp.data.msg,
                            type: 'success'
                        });
                        this.getAll();
                    } else {
                        alert(resp.data.msg);
                    }
                })
            },
            //添加学生
            addStudent() {
                //提交表单验证
                this.$refs.form1.validate((valid) => {
                    // 判断是否通过验证
                    if (valid) {
                        // 通过验证，提交数据
                        axios.post("/student/add", this.form1).then(resp => {
                            console.log(resp);
                            if (resp.data.code === 200) {
                                //添加成功，重新加载数据
                                this.dialogFormVisible1 = false;
                                this.getAll();
                            } else {
                                // 添加失败
                                this.$notify.error({
                                    title: '添加失败',
                                    message: resp.data.msg
                                });
                                alert(resp.data.msg);
                            }
                        })
                    } else {
                        // 未通过验证
                        console.log('error submit!!');
                        return false;
                    }
                });

            },
            //上传成功的回调 res: 服务器返回的数据，file:上传的文件对象
            handleAvatarSuccess(res, file) {
                this.imageUrl = res.data;//把返回的路径赋值给imageUrl
                this.form1.headimg = this.imageUrl;//把图片路径赋值给表单
                this.form2.headimg = this.imageUrl;
            },
            //上传之前的回调
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 10240 / 10240 < 10;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 10MB!');
                }
                // 返回true表示上传，返回false表示不上传
                return isJPG && isLt2M;
            },
            //删除学生
            deleteById(id) {
                axios.delete("/student/delete?id=" + id).then(resp => {
                    //alert(resp.data.id);
                    this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {//成功
                        //删除操作
                        if (resp.data.code === 200) {
                            //删除成功，重新加载数据
                            this.getAll();
                        } else {
                            alert(resp.data.msg);
                        }
                        //提示信息
                        this.$notify({
                            title: '成功',
                            message: resp.data.msg,
                            type: 'success'
                        });
                    }).catch(() => {//取消提示信息
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });

                })
            },
            //使用方法清空表单，和图片路径
            resetForm(){
                this.$refs.form1.resetFields();
                this.imageUrl = '';
            }
        }
    })
</script>
</html>
